<template>
  <div class="divBox">
    <div class="selCard mb14">
      <el-form size="small" inline :model="tableFrom" ref="searchForm" label-width="85px">
        <el-form-item label="创建时间：">
          <el-date-picker
            v-model="timeVal"
            value-format="yyyy/MM/dd"
            format="yyyy/MM/dd"
            size="small"
            type="daterange"
            placement="bottom-end"
            placeholder="自定义时间"
            style="width: 280px;"
            :picker-options="pickerOptions"
            @change="onchangeTime"
          />
        </el-form-item>
       
        <el-form-item label="商户名称：" prop="mer_id">
          <el-select
            v-model="tableFrom.mer_id"
            clearable
            filterable
            remote 
            :remote-method="getMerSelect"
            placeholder="请选择"
            class="selWidth"
            @visible-change="getMerSelect()"
            @change="getMerSelect(),getList(1)"
          >
            <el-option
              v-for="item in merSelect"
              :key="item.mer_id"
              :label="item.mer_name"
              :value="item.mer_id"
            />
          </el-select>
        </el-form-item>
       
        <el-form-item label="选择酒店：" prop="hotel_id">
          <el-select
            v-model="tableFrom.hotel_id"
            filterable
            remote
            reserve-keyword
            placeholder="请选择酒店"
            :remote-method="remoteMethod"
            :loading="hotelLoading">
            <el-option
              v-for="item in hotelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单号：" prop="order_no">
          <el-input
            v-model="tableFrom.order_no"
            @keyup.enter.native="getList(1)"
            placeholder="请输入订单号"
            class="selWidth"
            clearable
          />
        </el-form-item>

        <el-form-item label="关键字：" prop="keywords">
          <el-input
            v-model="tableFrom.keywords"
            @keyup.enter.native="getList(1)"
            placeholder="请输入订单号/联系方式"
            class="selWidth"
            clearable
          />
        </el-form-item>

        <el-form-item label="手机号：" prop="guest_phone">
          <el-input
            v-model="tableFrom.guest_phone"
            @keyup.enter.native="getList(1)"
            placeholder="请输入手机号"
            class="selWidth"
            clearable
          /> 
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="getList(1)">搜索</el-button>
          <el-button size="small" @click="searchReset()">重置</el-button> 
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <el-tabs v-model="tableFrom.status" @tab-click="getList(1)">
        <!-- <el-tab-pane v-for="(item,index) in headeNum" :key="index" :name="item.order_type.toString()" :label="item.title +'('+item.count +')' " /> -->
       <!-- 0:待支付 1:待确认 2:已确认 3:已入住 4:已完成 5:已取消，-1.待退款 2.已退款 -->
        <el-tab-pane name="9999" :label="'全部' +'('+(orderChartType.all||0)+')' " />
        <el-tab-pane name="0" :label="'待付款' +'('+(orderChartType.unpaid||0)+')' " />
        <el-tab-pane name="1" :label="'待确认' +'('+(orderChartType.unConfirm||0)+')' " />
        <el-tab-pane name="2" :label="'待入住' +'('+(orderChartType.yesConfirm||0)+')' " />
        <el-tab-pane name="3" :label="'已入住' +'('+(orderChartType.goHotel||0)+')' " />
        <el-tab-pane name="4" :label="'已完成' +'('+(orderChartType.complete||0)+')' " />
        <el-tab-pane name="5" :label="'已取消' +'('+(orderChartType.cancel||0)+')' " />
        <el-tab-pane name="-1" :label="'待退款' +'('+(orderChartType.noRefund||0)+')' " />
        <el-tab-pane name="-2" :label="'已退款' +'('+(orderChartType.refund||0)+')' " />
      </el-tabs>
      <div class="mt5">
        <el-button size="small" type="primary" class="mb20" @click="exports">导出列表</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        size="small"
        class="table"
        highlight-current-row
        :cell-class-name="addTdClass"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="产品总价：">
                <span>{{ props.row.total_amount | filterEmpty }}</span>
              </el-form-item>
              <el-form-item label="下单时间：">
                <span>{{ props.row.create_time | filterEmpty }}</span>
              </el-form-item>
              <el-form-item label="用户备注：">
                <span>{{ props.row.remark | filterEmpty }}</span>
              </el-form-item>
              <el-form-item label="商家备注：">
                <span>{{ props.row.mer_mark | filterEmpty }}</span>
              </el-form-item>
              <el-form-item label="平台备注：">
                <span>{{ props.row.admin_mark | filterEmpty }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="订单编号" min-width="150">
          <template slot-scope="scope">
            <span style="display: block;" v-text="scope.row.order_no" />
          </template>
        </el-table-column>
     
        <el-table-column prop="guest_phone" label="订购人" min-width="120" />
        <el-table-column label="商户名称" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.merchant ? scope.row.merchant.mer_name :'' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="酒店名称" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.hotel_name ? scope.row.hotel_name  :'' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="房间信息" min-width="280">
          <template slot-scope="scope">
            <div
              class="tabBox acea-row row-middle"
            >
              <div class="demo-image__preview">
                <el-image
                   v-if="scope.row.hotelRoomType.slider_image"
                  :src="JSON.parse(scope.row.hotelRoomType.slider_image)[0]"
                  :preview-src-list="[JSON.parse(scope.row.hotelRoomType.slider_image)[0]]"
                />
              </div>
              <span
                class="tabBox_tit"
              >{{ scope.row.hotelRoomType.name + ' | ' }}{{  scope.row.hotelRoomPackage.name }}</span>
      
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入住日期" min-width="120">
          <template slot-scope="scope">
             <span
                class="tabBox_tit"
              >  {{  scope.row.check_in_date + ' / '+ scope.row.check_out_date}}</span>
          </template>
        </el-table-column>
       <el-table-column prop="nights" label="入住天数" min-width="80" />
        <el-table-column prop="room_count" label="房间数量" min-width="80" />
        <el-table-column label="实际支付" min-width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.pay_amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已退金额" min-width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.refund_price? scope.row.refund_price:'--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" min-width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.pay_status === 1">{{ scope.row.pay_type | orderPayType }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.pay_status == 0 ? "未支付" : "已支付" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" min-width="80">
          <template slot-scope="scope">
              <span>{{ scope.row.status | hotelOrderStatusFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="serviceScore" label="下单时间" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="onOrderDetails(scope.row.id)">详情</el-button>
            <el-button type="text" size="small"  v-if="scope.row.pay_status==1"  @click="refundShowClick(scope.row)">退款</el-button>
            <el-button v-if="scope.row.order_status == -1 && scope.row.refund_status == 1" type="text" size="small" @click="onRefundDetail(scope.row.order_no)">查看退款单</el-button>
            <el-button type="text" size="small" style="color: #ED4014;" v-if="scope.row.pay_status && scope.row.order_status==1"  @click="onOrderConfirm(scope.row.id)">确认订单</el-button>
            <el-button type="text" size="small" style="color: #ED4014;" v-if="scope.row.pay_status && scope.row.order_status==2"  @click="onOrderConfirmGoRoom(scope.row.id)">确认入住</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    
    <!--详情-->
    <order-detail
      ref="orderDetail"
      :orderId="orderId"
      @closeDrawer="closeDrawer"
      @changeDrawer="changeDrawer"
      :drawer="drawer"
    ></order-detail>
      <!--退款-->
    
          <!-- 立即退款 -->
      <el-dialog title="立即退款" :visible.sync="refundShow" width="40%" >
         <el-form :model="refundForm"  ref="refundForm" label-width="100px" class="formValidate mt20" >
            <el-form-item label="订单号："  prop="order_id">
              <el-input v-model="refundForm.order_id" style="width:50%" disabled placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="退款金额：" prop="refund_price">
              <el-input-number  :min="0" :max="Maxprice" v-model="refundForm.refund_price" placeholder="请输入"  />
            </el-form-item> 
            <el-form-item label="备注：" prop="remark">
                <el-input maxlength="100" :show-word-limit="true" type="textarea" style="width:60%"  v-model="refundForm.refund_reason_wap_explain" placeholder="输入退款原因"></el-input>
            </el-form-item>
           
            <el-form-item class="acea-row row-center-wrapper">
              <el-button type="primary"  @click="sumRefund('refundForm')">提交退款</el-button>
              <el-button @click="refundShow=false">取消</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
      <!-- 立即退款 -->
  </div>
</template>

<script>
import { merSelectListApi ,hotelOrderChartApi, hotelOrderListApi ,exportOrderApi,
   hotelOrderAdminRefundApi,hotelConfirmOrderApi,hotelConfirmGoRoomApi} from "@/api/product";
import orderDetail from './orderDetails.vue';
import createWorkBook from '@/utils/newToExcel.js';
import { fromList } from "@/libs/constants.js";
import timeOptions from '@/utils/timeOptions';
import { tourTypr } from "@/filters";
import { roterPre } from "@/settings";
export default {
  components: { orderDetail },
  data() {
    return {
         roterPre: roterPre,
      productOptions: [],
      productLoading: false,
      pickerOptions: timeOptions,
      orderId: 0,
      tableData: {
        data: [],
        total: 0,
      },
      activity: [
        {name: "普通订单",type: 0},
        {name: "秒杀订单",type: 1},
        {name: "预售订单",type: 2},
        {name: "助力订单",type: 3},
        {name: "拼团订单",type: 4}
      ],
      listLoading: true,
      tableFrom: {
        order_no: "",
        hotel_id: '',
        keywords: "",
        status: '',
        date: "",
        guest_phone: "",
        mer_id: "",
        page: 1,
        limit: 10,
      },
      dliveryWayList: [
        { value: 1, label: '快递订单' },
        { value: 2, label: '配送订单' },
        { value: 4, label: '核销订单' },
        { value: 3, label: '虚拟发货' },
        { value: 6, label: '自动发货' }
      ], //发货方式
      productTypeList: [
        { value: 1, label: '实物产品' },
        { value: 2, label: '虚拟产品' },
        { value: 3, label: '卡密产品' }
      ], //产品类型
      orderChartType: {},
      timeVal: [],
      timeVal2: [],
      fromList: fromList,
      selectionList: [],
      ids: "",
      uid: "",
      visibleDetail: false,
      tableFromLog: {
        page: 1,
        limit: 10,
      },
      tableDataLog: {
        data: [],
        total: 0,
      },
      LogLoading: false,
      dialogVisible: false,
      cardLists: [],
      orderDatalist: null,
      merSelect: [],
      drawer: false,
      userDawer: false,
      hotelOptions: [],
      hotelLoading: false,
      refundShow: false,
      refundForm:{
        order_id:'',
        refund_price:0,
        refund_message:''
      },
       Maxprice:0,
    };
  },
  mounted() {
    if (this.$route.query.hasOwnProperty("order_sn")) {
      this.tableFrom.order_sn = this.$route.query.order_sn;
    } else {
      this.tableFrom.order_sn = "";
    }
    this.headerList();
    this.getMerSelect();
    this.getList('');
  },
  // 被缓存接收参数
  activated() {
    if (this.$route.query.hasOwnProperty("order_sn")) {
      this.tableFrom.order_sn = this.$route.query.order_sn;
    } else {
      this.tableFrom.order_sn = "";
    }
    this.headerList();
    this.getMerSelect();
    this.getList('');
  },
  methods: {
    
      // 退款
      refundShowClick(item){
        var price = 0
        if(item.pay_amount-item.refund_price<=0) {
          price = 0
        } else {
          price = item.pay_amount-item.refund_price
        }
        this.Maxprice = price
        this.refundForm = {
          order_id:item.order_no,
          refund_price: price,
          refund_message: ''
        }
        this.refundShow = true
      },
          // 提交退款
      sumRefund(){
        if(this.refundForm.refund_price<=0) {
          this.$message.error('退款不能小于等于0')
        } else{
          // console.log(this.refundForm)
          this.$loading();
          hotelOrderAdminRefundApi(this.refundForm).then( (res) => {            
            this.refundShow = false;
            this.getList('')
            this.headerList()
            this.$loading().close();    
          }).catch((res) => {
            this.$loading().close();   
              this.$message.error(res.message);
          });
        }
        //TODO
      },
  

       remoteMethod(query){
        if (query !== '') {
          this.hotelLoading = true;

          hotelLstApi({ keyword: query })
          .then(res => {
            this.hotelLoading = false;
            this.hotelOptions = res.data.list;
          })
          .catch(res => {
            this.$message.error(res.message)
          })

            
        } else {
          this.hotelOptions = [];
        }
    },
   

 
    // 订单确认
    onOrderConfirm(id) {
      // this.$modalForm(orderRemarkApi(id)).then(() => this.getList(''))
      this.$confirm('是否确认订单, 是否继续?', '确认提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          hotelConfirmOrderApi(id).then(() => {
            this.getList('')
            this.headerList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    },
       // 订单确认入住
    onOrderConfirmGoRoom(id) {
      // this.$modalForm(orderRemarkApi(id)).then(() => this.getList(''))
      this.$confirm('是否确认入住, 是否继续?', '确认提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          hotelConfirmGoRoomApi(id).then(() => {
            this.getList('')
            this.headerList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    },
    /**重置 */
    searchReset(){
      this.timeVal = []
      this.timeVal2 = []
      this.tableFrom.date = ""
      this.$refs.searchForm.resetFields()
      this.getList(1)
    },
    // 退款详情页
    onRefundDetail(sn) {
      // this.$router.push({
      //   path: this.roterPre+"/product/hotel/refund/list?sn="+sn,
      //   query: {
      //     sn: sn,
      //   },
      // });
        this.$router.push(
          this.roterPre+"/product/hotel/refund/list?sn="+sn,
        );
    },
    // 订单筛选
    orderFilter(item) {
      let status = false;
      item.orderProduct.forEach((el) => {
        if (el.refund_num > 0 && el.refund_num < el.product_num) {
          status = true;
        }
      });
      return status;
    },
    // 表格某一行添加特定的样式
    addTdClass(val) {
      if (val.row.status > 0 && val.row.pay_status == 1) {
        for (let i = 0; i < val.row.orderProduct.length; i++) {
          if (val.row.orderProduct[i].refund_num > 0 && val.row.orderProduct[i].refund_num < val.row.orderProduct[i].product_num) {
            return "row-bg";
          }
        }
      } else {
        return " ";
      }
    },
    // 商户列表；
    getMerSelect(query) {
      merSelectListApi({keyword: query})
        .then((res) => {
          this.merSelect = res.data;
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    // 用户信息
    onUserDetails(uid) {
      this.uid = uid
      this.userDawer = true
      this.$refs.userDetails.getData(uid,false,true);
    },
    closeDrawer() {
      this.drawer = false
      this.userDawer = false
    },
    changeDrawer(v) {
      this.drawer = v;
      this.userDawer = v;
    },
    async exports() {
      let excelData = JSON.parse(JSON.stringify(this.tableFrom)), data = []
      excelData.page = 1
      let pageCount = 1
      let lebData = {};
      for (let i = 0; i < pageCount; i++) {
        lebData = await this.downData(excelData)
        pageCount = Math.ceil(lebData.count/excelData.limit)
        if (lebData.export.length) {
          data = data.concat(lebData.export)
          excelData.page++
        }
      }
      createWorkBook(lebData.header, lebData.title, data, lebData.foot,lebData.filename);
      return
    },
    /**订单列表 */
    downData(excelData) {
      return new Promise((resolve, reject) => {
        exportOrderApi(excelData).then((res) => {
          return resolve(res.data)
        })
      })
    },
    // 导出
    exportRecord() {
      exportOrderApi(this.tableFrom)
        .then((res) => {
          const h = this.$createElement;
          this.$msgbox({
            title: '提示',
            message: h('p', null, [
              h('span', null, '文件正在生成中，请稍后点击"'),
              h('span', { style: 'color: teal' }, '导出记录'),
              h('span', null, '"查看~ '),
            ]),
            confirmButtonText: '我知道了',
          }).then(action => {

          });
        })
        .catch((res) => {
          this.$message.error(res.message)
        })
    },
    // 详情
    onOrderDetails(id) {
      this.orderId = id;
      this.$refs.orderDetail.getInfo(id);
      this.drawer = true;
      // this.$refs.orderDetail.onOrderDetails(id);
      // this.$refs.orderDetail.onOrderLog(id);
    },
    pageChangeLog(page) {
      this.tableFromLog.page = page;
      this.getList('');
    },
    handleSizeChangeLog(val) {
      this.tableFromLog.limit = val;
      this.getList('');
    },
    // 选择时间
    selectChange(tab) {
      this.tableFrom.date = tab;
      this.tableFrom.page = 1;
      this.timeVal = [];
      this.getList(1);
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e;
      this.tableFrom.date = e ? this.timeVal.join("-") : "";
      this.tableFrom.page = 1;
      this.getList(1);
    },
    onchangeTime2(e) {
      this.timeVal2 = e;
      this.tableFrom.go_date = e ? this.timeVal2.join("-") : "";
      this.tableFrom.page = 1;
      this.getList(1);
    },
    // 列表
    getList(num) {
      this.listLoading = true;
      this.tableFrom.page = num ? num : this.tableFrom.page;
      hotelOrderListApi(this.tableFrom)
        .then((res) => {
          this.tableData.data = res.data.list;
          this.tableData.total = res.data.count;
        //   this.cardLists = res.data.stat;
          this.listLoading = false;
        })
        .catch((res) => {
          this.$message.error(res.message);
          this.listLoading = false;
        });
    },
  
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList('');
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList('');
    },
    headerList() {
      hotelOrderChartApi()
        .then((res) => {
          this.orderChartType = res.data;
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-table-expand ::v-deep label {
  width: 83px !important; 
}
.el-dropdown-link {
  cursor: pointer;
  color: var(--prev-color-primary);
  font-size: 12px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.tabBox_tit {
  max-width: 60%;
  font-size: 12px !important;
  margin: 0 2px 0 10px;
  letter-spacing: 1px;
  padding: 5px 0;
  box-sizing: border-box;
}
::v-deep .row-bg .cell {
  color: red !important;
}
</style>
